package com.googlecode.scup.parser;

import com.googlecode.scup.grammar.grammarspart.Symbol;
import com.googlecode.scup.grammar.readers.SimpleReader;
import com.googlecode.scup.parser.actionstates.ActionState;
import com.googlecode.scup.parser.actionstates.ActionStateType;
import com.googlecode.scup.parser.automat.Automat;

import java.util.*;
import java.util.regex.*;
import java.io.IOException;

public class Parser {
    private List<Map<Symbol, ActionState>> actionTable = null;
    private ActionState act;
    private List<Map<Symbol, ActionState>> gotoTable;

    public Parser(String path) {
        //TODO: may be rewriting later this terrible constructor :o
        try {
            Automat automat = new Automat(new SimpleReader(path).getGrammar());
            actionTable = ActionTable.createActionTable(automat);
            gotoTable = ActionTable.createGotoTable(automat);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Parser(char[] stream) {
        //TODO: may be rewriting later this terrible constructor :o
        try {
            Automat automat = new Automat(new SimpleReader(stream).getGrammar());
            actionTable = ActionTable.createActionTable(automat);
            gotoTable = ActionTable.createGotoTable(automat);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public ActionState action(Integer s, Symbol a) {
    	Map<Symbol, ActionState> nonterminals = actionTable.get(s);

    	for (Symbol symbol : nonterminals.keySet()) {
    		try {
    			Pattern p = Pattern.compile(symbol.getName());
    			Matcher m = p.matcher(a.getName());
    			if (m.matches()) {
    				return nonterminals.get(symbol);
    			}

    		} catch (PatternSyntaxException e) {
    		}
    	}

    	return nonterminals.get(a);
    }

    public boolean match(String input) {
        Stack<Symbol> symbolsStack = new Stack<Symbol>();
        Stack<Integer> stack = new Stack<Integer>();

        InputStream inputStream = new InputStream(input + " $");

        stack.push(0);
        inputStream.nextToken();

        try{
            do {
                act = action(stack.peek(), inputStream.getToken());
                act.doAction(symbolsStack, stack, inputStream, gotoTable);
            } while (act.getType() != ActionStateType.ACCEPT);
        } catch (Exception ex) {
            return false;
        }
        return true;
    }
}
